﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using Facebook;
using GeoFinderClientApp.Converters;
using GeoFinderClientApp.Model;
using GeoFinderClientApp.Web;

namespace GeoFinderClientApp.View
{
    public partial class FacebookLogin : PhoneApplicationPage
    {

        private FacebookClient _fbClient;

        // Constructor
        public FacebookLogin()
        {
            InitializeComponent();
            _fbClient = new FacebookClient();
            WebCore.SubscriptionCompleted += new EventHandler<LoginEventArgs>(_webCore_SubscriptionCompleted);
            FacebookLoginBrowser.Loaded += new RoutedEventHandler(FacebookLoginBrowser_Loaded);
        }

        void _webCore_SubscriptionCompleted(object sender, LoginEventArgs e)
        {
            WebCore.Task = new System.Threading.Thread(WebCore.MainMethod);
            WebCore.Task.Start();
            WebCore.RefreshAll();
        }

        // Browser control is loaded and fully ready for use
        void FacebookLoginBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            if (!WebCore.LoggedIn)
            {
                LoginToFacebook();
            }
        }

        // This handles the display a little and also creates the initial URL to navigate to in the browser control
        private void LoginToFacebook()
        {
            TitlePanel.Visibility = Visibility.Visible;
            FacebookLoginBrowser.Visibility = Visibility.Visible;
            var loginParameters = new Dictionary<string, object>
                                      {
                                          { "response_type", "token" }
                                          // { "display", "touch" } // by default for wp7 builds only (in Facebook.dll), display is set to touch.
                                      };

            var navigateUrl = FacebookOAuthClient.GetLoginUrl(WebCore.APP_ID, null, WebCore.EXTENDED_PERMISSIONS, loginParameters);

            FacebookLoginBrowser.Navigate(navigateUrl);
        }

        private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult oauthResult;
            if (FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    FacebookLoginBrowser.Visibility = System.Windows.Visibility.Collapsed;
                    progressBar.Visibility = System.Windows.Visibility.Visible;
                    _fbClient = new FacebookClient(oauthResult.AccessToken);
                    WebCore._fbClient = _fbClient;
                    WebCore.LoggedIn = true;

                    WebCore.FirstTime(Dispatcher);
                }
                else
                {
                    MessageBox.Show(oauthResult.ErrorDescription);
                }
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            WebCore.FacebookDataRecived += new EventHandler<LoginEventArgs>(WebCore_FacebookDataRecived);

            //if (State.ContainsKey("client")){
            //    _fbClient = (FacebookClient) State["client"];
            //}

            //if (State.ContainsKey("loginSecceded"))
            //{
            //    _loggedIn = (bool)State["loginSucceded"];
            //}

            //if (WebCore.LoggedIn)
            //{
            //    if (NavigationService.CanGoBack)
            //    {
            //        NavigationService.GoBack();
            //    }
            //    else
            //    {
            //        NavigationService.Navigate(new Uri("MainPage.xaml", UriKind.Relative));
            //    }
            //}

        }

        void WebCore_FacebookDataRecived(object sender, LoginEventArgs e)
        {
            WebCore.FacebookDataRecived -= WebCore_FacebookDataRecived;
            if (NavigationService.Source.Equals(new Uri("/View/FacebookLogin.xaml", UriKind.Relative)))
            {
                NavigationService.Navigate(new Uri("/View/ApplicationsMain.xaml", UriKind.Relative));
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            //if (!State.ContainsKey("client"))
            //{
            //    State.Add("client", _fbClient);
            //}
            //else
            //{
            //    State["client"] = FriendList;
            //}

            //if (!State.ContainsKey("loginSucceded"))
            //{
            //    State.Add("loginSucceded", Me);
            //}
            //else
            //{
            //    State["loginSucceded"] = Me;
            //}

            progressBar.Visibility = System.Windows.Visibility.Collapsed;
            FacebookLoginBrowser.Visibility = System.Windows.Visibility.Visible;
        }
    }
}
